import promise from 'es6-promise';
import babelpolyfill from 'babel-polyfill'
// import Vue from 'vue'
import App from './App'


import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
import routes from './routes/index'
import Mock from './mock'
import comm from './common/js/cofig'
import 'font-awesome/scss/font-awesome.scss'
import '@/assets/menuIcon/iconfont.css'
import axios from 'axios';
import Home from './views/Home.vue'
import './styles/comm.css'

import VueQriously from 'vue-qriously'
Vue.use(VueQriously)
promise.polyfill();

function _import(s) {
  return resolve => require(['./views' + s], resolve);
};
promise.polyfill();
// babelpolyfill;
Vue.use(ELEMENT);
Vue.use(VueRouter)
Vue.use(Vuex)
Vue.use(comm)

//NProgress.configure({ showSpinner: false });

import {
  query,
  menu_tree,
  userinfo,
  company_get_my
} from './api/api';
const router = new VueRouter({
  routes
})

axios.defaults.withCredentials = true;
Vue.prototype.$http = axios;

Vue.config.productionTip = true

var getRouter;
let registerRouteFresh = true
router.afterEach((to, from) => {
  //会在任意路由跳转后执行

  let key = JSON.parse(localStorage.getItem("key"));
  if (!getRouter && key) { //不加这个判断，路由会陷入死循环
    getRouter = localStorage.getItem('menu');//动态路由
    if (getRouter) {
      getRouter = JSON.parse(getRouter);//路由转对象
      getRouter = filterAsyncRouter(getRouter);
      router.options.routes = [];
      for (let i = getRouter.length - 1; i >= 0; i--) {
        router.options.routes.unshift(getRouter[i])
      }
      router.addRoutes(getRouter);
    } else { //从localStorage拿到了路由
      let params = {
        token: key
      };
      menu_tree(params).then(r => {
        if (r.code !== 0) {
          // this.$message({
          //   message: r.message,
          //   type: "error"
          // });
        } else {
          getRouter = r.data;
          getRouter = filterAsyncRouter(getRouter);
          router.options.routes = [];
          localStorage.setItem("menu", JSON.stringify(getRouter));
          for (let i = getRouter.length - 1; i >= 0; i--) {

            router.options.routes.unshift(getRouter[i]);

          }
          router.addRoutes(getRouter);
          // location.reload();
          return false;
          // global.antRouter = router;



          // next()
          // return false;
          // console.log(router)

          // router
        }
      });
    }
  } else {
    // next()
  }
})
router.beforeEach((to, from, next) => {

  // localStorage.setItem('new',JSON.stringify({'path':to.path}))//保存路由
  let hdpi = sessionStorage.getItem('hdpi');

  if (to.path == '/') {

    next('/home_page');
    return false;
  }
  if (to.path == '/account/register' || to.path == '/account/ft_password' || to.path == '/Provision') {
    next();
    return false;
  }

  //NProgress.start();

  let key = JSON.parse(localStorage.getItem('key'));
  if (!key) {
    getRouter = "";
  }
  if (!key && to.path != '/login') {
    next({
      path: '/login'
    });
    return false
  } else {
    let Params = {
      token: key,
      pageNo: 1,
      pageSize: 20
    };
    if (key) {

      axios.interceptors.request.use(
        config => {
          if (key) { // 判断是否存在token，如果存在的话，则每个http header都加上token
            key = JSON.parse(localStorage.getItem('key'))
            config.headers.token = key;
          } else {}

          // console.log(config)
          return config;
        },
        err => {

          return Promise.reject(err);
        });
      axios.interceptors.response.use(function (response) {
        // 处理响应数据
        return response;
      }, function (error) {
        // 处理响应失败
        Vue.prototype.$message({
          message: '请求网络失败,请重试',
          type: 'warning'
        });
        return Promise.reject(error);
      });


    }
    if (!getRouter && key) { //不加这个判断，路由会陷入死循环
      getRouter = localStorage.getItem('menu');
      if (getRouter) {
        getRouter = JSON.parse(getRouter);
        getRouter = filterAsyncRouter(getRouter);
        console.log(router,777);
        router.options.routes = [];
        for (let i = getRouter.length - 1; i >= 0; i--) {
          router.options.routes.unshift(getRouter[i])
        }
        router.addRoutes(getRouter);
      } else { //从localStorage拿到了路由
        // let key = JSON.parse(localStorage.getItem("key"));
        let params = {
          token: key
        };
        menu_tree(params).then(r => {
          if (r.code !== 0) {
            // this.$message({
            //   message: r.message,
            //   type: "error"
            // });
          } else {
            getRouter = r.data;

            getRouter = filterAsyncRouter(getRouter);

       
            router.options.routes = [];
            localStorage.setItem("menu", JSON.stringify(getRouter));
            for (let i = getRouter.length - 1; i >= 0; i--) {

              router.options.routes.unshift(getRouter[i]);

            }
 
            router.addRoutes(getRouter);
  
            // location.reload();
            return false;
            // global.antRouter = router;



            // next()
            // return false;
            // console.log(router)

            // router
          }

        
        });
      
      }
      
    // var getLastUrl=(str,yourStr)=>str.slice(str.lastIndexOf(yourStr));
    //   if (localStorage.getItem('new')) {
    //     var c = JSON.parse(localStorage.getItem('new'));
    //     let lastUrl = getLastUrl(window.location.href, '/');
    //     console.log(lastUrl)
    //     console.log(c.path)
    //     console.log(to)
    //     if (c.path == to.path) { //动态路由页面的刷新事件
    //       console.log('tx')
    //       localStorage.removeItem('new');
    //       let newRoutes = routes.concat([{
    //         path: c.path,
    //         component: _import(c.path)
    //       }])
    //       console.log(newRoutes)
    //       router.addRoutes(newRoutes)
    //       router.replace(c.path) //replace,保证浏览器回退的时候能直接返回到上个页面，不会叠加
         
    //     }
    //   }
      // console.log(router)
      
  // next()
    } else {
      // next()
    }
    // console.log(localStorage.getItem('new'))
    // if (localStorage.getItem('new')) {
    //   var c = JSON.parse(localStorage.getItem('new'));
    //   var lastUrl=to.path;
    //   console.log(lastUrl)
    //   console.log( c.path)
    //   console.log(c.path==lastUrl)
    //   if (c.path==lastUrl) { //动态路由页面的刷新事件

    //    localStorage.removeItem('new');
    //    console.log(getRouter)
    //    router.addRoutes(getRouter)
    //   //  router.replace(c.path) //replace,保证浏览器回退的时候能直接返回到上个页面，不会叠加

    //   }else{

    //   localStorage.setItem('new',JSON.stringify(to))//保存路由
    //   } 
    //  }else{
    //   localStorage.setItem('new',JSON.stringify(to))//保存路由
    //  }

    if (to.matched.length === 0) { //如果未匹配到路由
      from.name ? next({
        name: from.name
      }) : next(to); //如果上级也未匹配到路由则跳转登录页面，如果上级能匹配到则转上级路由
    } else {
      next(); //如果匹配到正确跳转
    }
  }


})

function routerGo(to, next) {
  getRouter = filterAsyncRouter(getRouter) //过滤路由
  router.addRoutes(getRouter) //动态添加路由

  global.antRouter = getRouter //将路由数据传递给全局变量，做侧边栏菜单渲染工作
  next({
    ...to,
    replace: true
  })
}

function saveObjArr(name, data) { //localStorage 存储数组对象的方法
  localStorage.setItem(name, JSON.stringify(data))
}

function getObjArr(name) { //localStorage 获取数组对象的方法
  return JSON.parse(sessionStorage.getItem(name)); 

}

function filterAsyncRouter(asyncRouterMap) { //遍历后台传来的路由字符串，转换为组件对象
  const accessedRouters = asyncRouterMap.filter(route => {
    if (route.path) {
      // if (route.component === 'Layout') { //Layout组件特殊处理
      //   route.component = Layout
      // } else {
      if (route.actionList) { 
        route.params = route.actionList;
      }
      if (route.path == '/' || route.children) {
        route.component = Home;
      } else {

        route.component = _import(route.path)
      }
      // }
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })

  return accessedRouters
}

new Vue({
  //el: '#app',
  //template: '<App/>',
  router,
  store,
  // store,
  components: {
    comm
  },
  render: h => h(App)
}).$mount('#app')